<template>
  <div class="admin-panel">
    <div class="admin-header">
      <h1>管理后台</h1>
      <el-button @click="$router.push('/')" type="primary">返回首页</el-button>
    </div>

    <el-tabs v-model="activeTab" class="admin-tabs">
      <!-- 电影管理 -->
      <el-tab-pane label="电影管理" name="movies">
        <div class="section-header">
          <h2>电影管理</h2>
          <div class="header-actions">
            <el-input
              v-model="movieSearchQuery"
              placeholder="搜索电影名称或导演..."
              @input="handleMovieSearch"
              style="width: 250px; margin-right: 10px;"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="showMovieDialog()">添加电影</el-button>
          </div>
        </div>

        <el-table :data="filteredMovies" v-loading="moviesLoading" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="poster_image" label="海报" width="100">
            <template #default="scope">
              <el-image :src="scope.row.poster_image" style="width: 60px; height: 80px" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="电影名称" width="150" />
          <el-table-column prop="director" label="导演" width="120" />
          <el-table-column prop="release_date" label="上映日期" width="120" />
          <el-table-column prop="rating" label="评分" width="80" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="showMovieDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteMovie(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 评论管理 -->
      <el-tab-pane label="评论管理" name="reviews">
        <div class="section-header">
          <h2>评论管理</h2>
          <el-button @click="fetchReviews" :loading="reviewsLoading">刷新</el-button>
        </div>

        <el-table :data="reviews" v-loading="reviewsLoading" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="movie_title" label="电影" width="150" />
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="rating" label="评分" width="80">
            <template #default="scope">
              <el-rate v-model="scope.row.rating" disabled show-score />
            </template>
          </el-table-column>
          <el-table-column prop="content" label="评论内容" min-width="200" />
          <el-table-column prop="created_at" label="评论时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="danger" @click="deleteReview(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 订单管理 -->
      <el-tab-pane label="订单管理" name="orders">
        <div class="section-header">
          <h2>订单管理</h2>
          <div class="header-actions">
            <el-input
              v-model="orderSearchQuery"
              placeholder="搜索订单号、用户名或电影名称..."
              @input="handleOrderSearch"
              style="width: 300px; margin-right: 10px;"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button @click="fetchOrders" :loading="ordersLoading" style="margin-right: 10px;">刷新</el-button>
            <el-button type="primary" @click="showOrderDialog()">添加订单</el-button>
          </div>
        </div>

        <el-table :data="filteredOrders" v-loading="ordersLoading" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="order_number" label="订单号" width="180" />
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="movie_title" label="电影" width="150" />
          <el-table-column prop="showtime" label="场次" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.showtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="seat" label="座位" width="120" />
          <el-table-column prop="price" label="价格" width="80">
            <template #default="scope">
              ￥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ getOrderStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="320">
            <template #default="scope">
              <el-select 
                v-model="scope.row.status" 
                @change="updateOrderStatus(scope.row)"
                size="small"
                style="margin-right: 8px; width: 100px;"
              >
                <el-option label="待处理" value="pending" />
                <el-option label="已确认" value="confirmed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
              <el-button 
                size="small" 
                @click="showOrderDialog(scope.row)"
                style="margin-right: 8px;"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteOrder(scope.row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 用户管理 -->
      <el-tab-pane label="用户管理" name="users">
        <div class="section-header">
          <h2>用户管理</h2>
          <div class="header-actions">
            <el-input
              v-model="userSearchQuery"
              placeholder="搜索用户名或邮箱..."
              @input="handleUserSearch"
              style="width: 250px; margin-right: 10px;"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="showUserDialog()">添加用户</el-button>
          </div>
        </div>

        <el-table :data="filteredUsers" v-loading="usersLoading" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="created_at" label="注册时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="showUserDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 电影添加/编辑对话框 -->
    <el-dialog 
      v-model="movieDialogVisible" 
      :title="movieForm.id ? '编辑电影' : '添加电影'"
      width="600px"
    >
      <el-form :model="movieForm" label-width="100px">
        <el-form-item label="电影名称" required>
          <el-input v-model="movieForm.title" placeholder="请输入电影名称" />
        </el-form-item>
        
        <el-form-item label="导演">
          <el-input v-model="movieForm.director" placeholder="请输入导演姓名" />
        </el-form-item>
        
        <el-form-item label="主演">
          <el-input v-model="movieForm.actors" placeholder="请输入主演，逗号分隔" />
        </el-form-item>
        
        <el-form-item label="海报图片">
          <el-input v-model="movieForm.poster_image" placeholder="请输入图片路径" />
        </el-form-item>
        
        <el-form-item label="电影简介">
          <el-input 
            v-model="movieForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入电影简介"
          />
        </el-form-item>
        
        <el-form-item label="上映日期">
          <el-date-picker 
            v-model="movieForm.release_date" 
            type="date" 
            placeholder="请选择上映日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="时长(分钟)">
          <el-input-number 
            v-model="movieForm.duration_mins" 
            :min="1" 
            placeholder="请输入电影时长"
          />
        </el-form-item>
        
        <el-form-item label="评分">
          <el-input-number 
            v-model="movieForm.rating" 
            :min="0" 
            :max="10" 
            :precision="1"
            placeholder="请输入评分"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="movieDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMovie" :loading="saving">
          {{ movieForm.id ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户添加/编辑对话框 -->
    <el-dialog 
      v-model="userDialogVisible" 
      :title="userForm.id ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" required>
          <el-input v-model="userForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        
        <el-form-item :label="userForm.id ? '新密码' : '密码'" :required="!userForm.id">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            :placeholder="userForm.id ? '不填写则不修改密码' : '请输入密码'"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="userSaving">
          {{ userForm.id ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 订单添加/编辑对话框 -->
    <el-dialog 
      v-model="orderDialogVisible" 
      :title="orderForm.id ? '编辑订单' : '添加订单'"
      width="600px"
    >
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="用户" required>
          <el-select v-model="orderForm.user_id" placeholder="选择用户" style="width: 100%">
            <el-option 
              v-for="user in users" 
              :key="user.id" 
              :label="user.username" 
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="电影" required>
          <el-select v-model="orderForm.movie_id" placeholder="选择电影" style="width: 100%">
            <el-option 
              v-for="movie in movies" 
              :key="movie.id" 
              :label="movie.title" 
              :value="movie.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="场次时间" required>
          <el-date-picker 
            v-model="orderForm.showtime" 
            type="datetime" 
            placeholder="选择场次时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="座位" required>
          <el-input v-model="orderForm.seat" placeholder="请输入座位号，如：A区5排8座" />
        </el-form-item>
        
        <el-form-item label="价格" required>
          <el-input-number 
            v-model="orderForm.price" 
            :min="0" 
            :precision="2"
            placeholder="请输入票价"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="状态" required>
          <el-select v-model="orderForm.status" placeholder="选择订单状态" style="width: 100%">
            <el-option label="待处理" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder" :loading="orderSaving">
          {{ orderForm.id ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import request from '../utils/request'

// 页签状态
const activeTab = ref('movies')

// 电影管理
const movies = ref([])
const moviesLoading = ref(false)
const movieDialogVisible = ref(false)
const saving = ref(false)
const movieSearchQuery = ref('')

// 过滤后的电影列表
const filteredMovies = computed(() => {
  if (!movieSearchQuery.value) {
    return movies.value
  }
  
  const query = movieSearchQuery.value.toLowerCase()
  return movies.value.filter(movie => 
    movie.title.toLowerCase().includes(query) ||
    movie.director.toLowerCase().includes(query)
  )
})

// 处理电影搜索
const handleMovieSearch = () => {
  // computed 会自动更新，这里可以添加防抖逻辑
}

const movieForm = reactive({
  id: null,
  title: '',
  director: '',
  actors: '',
  poster_image: '',
  description: '',
  release_date: '',
  duration_mins: null,
  rating: null
})

// 评论管理
const reviews = ref([])
const reviewsLoading = ref(false)

// 订单管理
const orders = ref([])
const ordersLoading = ref(false)
const orderSearchQuery = ref('')
const orderDialogVisible = ref(false)
const orderSaving = ref(false)

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (!orderSearchQuery.value) {
    return orders.value
  }
  
  const query = orderSearchQuery.value.toLowerCase()
  return orders.value.filter(order => 
    order.order_number.toLowerCase().includes(query) ||
    order.username.toLowerCase().includes(query) ||
    order.movie_title.toLowerCase().includes(query)
  )
})

// 处理订单搜索
const handleOrderSearch = () => {
  // computed 会自动更新，这里可以添加防抖逻辑
}

const orderForm = reactive({
  id: null,
  user_id: null,
  movie_id: null,
  showtime: '',
  seat: '',
  price: null,
  status: 'pending'
})

// 用户管理
const users = ref([])
const usersLoading = ref(false)
const userDialogVisible = ref(false)
const userSaving = ref(false)
const userSearchQuery = ref('')

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!userSearchQuery.value) {
    return users.value
  }
  
  const query = userSearchQuery.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(query) ||
    user.email.toLowerCase().includes(query)
  )
})

// 处理用户搜索
const handleUserSearch = () => {
  // computed 会自动更新，这里可以添加防抖逻辑
}

const userForm = reactive({
  id: null,
  username: '',
  email: '',
  password: ''
})

// 获取电影列表
const fetchMovies = async () => {
  try {
    moviesLoading.value = true
    const res = await request.get('/admin/movies')
    if (res.data.success) {
      movies.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取电影列表失败')
  } finally {
    moviesLoading.value = false
  }
}

// 显示电影对话框
const showMovieDialog = (movie = null) => {
  if (movie) {
    // 编辑模式
    Object.assign(movieForm, movie)
    if (movieForm.release_date) {
      movieForm.release_date = new Date(movieForm.release_date)
    }
  } else {
    // 添加模式
    resetMovieForm()
  }
  movieDialogVisible.value = true
}

// 重置电影表单
const resetMovieForm = () => {
  Object.assign(movieForm, {
    id: null,
    title: '',
    director: '',
    actors: '',
    poster_image: '',
    description: '',
    release_date: '',
    duration_mins: null,
    rating: null
  })
}

// 保存电影
const saveMovie = async () => {
  try {
    saving.value = true
    
    const data = { ...movieForm }
    if (data.release_date) {
      data.release_date = data.release_date.toISOString().split('T')[0]
    }
    
    let res
    if (movieForm.id) {
      // 更新
      res = await request.put(`/admin/movies/${movieForm.id}`, data)
    } else {
      // 添加
      res = await request.post('/admin/movies', data)
    }
    
    if (res.data.success) {
      ElMessage.success(movieForm.id ? '电影更新成功' : '电影添加成功')
      movieDialogVisible.value = false
      fetchMovies()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 删除电影
const deleteMovie = async (movie) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除电影《${movie.title}》吗？此操作将同时删除相关的评论和订单。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.delete(`/admin/movies/${movie.id}`)
    if (res.data.success) {
      ElMessage.success('电影删除成功')
      fetchMovies()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取评论列表
const fetchReviews = async () => {
  try {
    reviewsLoading.value = true
    const res = await request.get('/admin/reviews')
    if (res.data.success) {
      reviews.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取评论列表失败')
  } finally {
    reviewsLoading.value = false
  }
}

// 删除评论
const deleteReview = async (review) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${review.username} 对《${review.movie_title}》的评论吗？`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.delete(`/admin/reviews/${review.id}`)
    if (res.data.success) {
      ElMessage.success('评论删除成功')
      fetchReviews()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    ordersLoading.value = true
    const res = await request.get('/admin/orders')
    if (res.data.success) {
      orders.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    ordersLoading.value = false
  }
}

// 更新订单状态
const updateOrderStatus = async (order) => {
  try {
    const res = await request.put(`/admin/orders/${order.id}/status`, {
      status: order.status
    })
    if (res.data.success) {
      ElMessage.success('订单状态更新成功')
    }
  } catch (error) {
    ElMessage.error('更新失败')
    fetchOrders() // 重新获取数据
  }
}

// 删除订单
const deleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.order_number} 吗？此操作无法撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.delete(`/admin/orders/${order.id}`)
    if (res.data.success) {
      ElMessage.success('订单删除成功')
      fetchOrders()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 显示订单对话框
const showOrderDialog = (order = null) => {
  if (order) {
    // 编辑模式 - 需要从用户名和电影名找到对应的ID
    const user = users.value.find(u => u.username === order.username)
    const movie = movies.value.find(m => m.title === order.movie_title)
    
    Object.assign(orderForm, {
      id: order.id,
      user_id: user ? user.id : null,
      movie_id: movie ? movie.id : null,
      showtime: order.showtime,
      seat: order.seat,
      price: order.price,
      status: order.status
    })
  } else {
    // 添加模式
    resetOrderForm()
  }
  orderDialogVisible.value = true
}

// 重置订单表单
const resetOrderForm = () => {
  Object.assign(orderForm, {
    id: null,
    user_id: null,
    movie_id: null,
    showtime: '',
    seat: '',
    price: null,
    status: 'pending'
  })
}

// 保存订单
const saveOrder = async () => {
  try {
    orderSaving.value = true
    
    const data = { ...orderForm }
    
    let res
    if (orderForm.id) {
      // 更新
      res = await request.put(`/admin/orders/${orderForm.id}`, data)
    } else {
      // 添加
      res = await request.post('/admin/orders', data)
    }
    
    if (res.data.success) {
      ElMessage.success(orderForm.id ? '订单更新成功' : '订单添加成功')
      orderDialogVisible.value = false
      fetchOrders()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    orderSaving.value = false
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    usersLoading.value = true
    const res = await request.get('/admin/users')
    if (res.data.success) {
      users.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    usersLoading.value = false
  }
}

// 显示用户对话框
const showUserDialog = (user = null) => {
  if (user) {
    // 编辑模式
    Object.assign(userForm, {
      id: user.id,
      username: user.username,
      email: user.email,
      password: ''
    })
  } else {
    // 添加模式
    resetUserForm()
  }
  userDialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    email: '',
    password: ''
  })
}

// 保存用户
const saveUser = async () => {
  try {
    userSaving.value = true
    
    const data = { ...userForm }
    
    let res
    if (userForm.id) {
      // 更新
      res = await request.put(`/admin/users/${userForm.id}`, data)
    } else {
      // 添加
      res = await request.post('/admin/users', data)
    }
    
    if (res.data.success) {
      ElMessage.success(userForm.id ? '用户更新成功' : '用户添加成功')
      userDialogVisible.value = false
      fetchUsers()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    userSaving.value = false
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？此操作将同时删除该用户的所有评论和订单。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.delete(`/admin/users/${user.id}`)
    if (res.data.success) {
      ElMessage.success('用户删除成功')
      fetchUsers()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    confirmed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    confirmed: '已确认',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchMovies()
  fetchReviews()
  fetchOrders()
  fetchUsers()
})
</script>

<style scoped>
.admin-panel {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.admin-header h1 {
  margin: 0;
  color: #333;
}

.admin-tabs {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.el-table {
  margin-top: 20px;
}

.el-dialog .el-form {
  padding: 20px;
}

@media (max-width: 768px) {
  .admin-panel {
    padding: 10px;
  }
  
  .admin-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>